//
//  SessionsController.swift
//  App
//
//  Created by melvyn on 2018/8/20.
//

import Foundation
import Vapor
import Crypto

class SessionsController: RouteCollection {
    
    func boot(router: Router) throws {
        let route = router.grouped("sessions")
        
        let basic = route.grouped(User.basicAuthMiddleware(using: BCryptDigest()))
        basic.post(use: signin)
        
        let bearer = route.grouped(User.tokenAuthMiddleware())
        bearer.delete(use: signout)
    }
    
    func signin(_ req: Request) throws -> EventLoopFuture<Token.Public> {
        let user = try req.requireAuthenticated(User.self)
        let token = try Token.generate(for: user)
        return token.save(on: req)
        .map({
            Token.Public.init(user: User.Public.init(user), token: $0)
        })
    }
    
    func signout(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
        let user = try req.requireAuthenticated(User.self)
        let token = req.http.headers.bearerAuthorization!.token
        
        return Token.query(on: req)
            .filter(\Token.uid, .equal, user.id!)
            .filter(\Token.token, .equal, token)
            .first()
            .unwrap(or: Abort.init(.forbidden))
            .flatMap({ $0.delete(on: req) })
            .transform(to: .ok)
    }
}
